package com.wjf.resourceservice.service.impl;

import com.wjf.resourceservice.entity.Music;
import com.wjf.resourceservice.mapper.MusicMapper;
import com.wjf.resourceservice.service.MusicService;
import com.wjf.common.entity.Result;
import com.wjf.resourceservice.feign.UserClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
import org.springframework.transaction.annotation.Transactional;

/**
 * 音乐服务实现类
 * 处理音乐相关的业务逻辑
 */
@Service
public class MusicServiceImpl implements MusicService {

    @Autowired
    private MusicMapper musicMapper;
    
    @Autowired
    private UserClient userClient;

    @Override
    public List<Music> getMusicList(int page, int size) {
        // 计算分页偏移量
        int offset = (page - 1) * size;
        return musicMapper.getMusicList(offset, size);
    }

    @Override
    public Music getMusicDetail(Long id) {
        return musicMapper.getMusicById(id);
    }

    @Override
    public String playMusic(Long id) {
        Music music = musicMapper.getMusicById(id);
        if (music == null) {
            return null;
        }
        // 增加播放次数并返回音乐URL
        musicMapper.incrementPlayCount(id);
        return music.getMusicUrl();
    }

    @Override
    public String downloadMusic(Long id) {
        Music music = musicMapper.getMusicById(id);
        if (music == null) {
            return null;
        }
        
        // 如果是VIP音乐，需要检查用户VIP状态
        if (music.getVipOnly()==1) {
            Result<Boolean> result = userClient.checkUserVip();
            if (!Boolean.TRUE.equals(result.getData())) {
                throw new RuntimeException("该音乐仅限VIP用户下载");
            }
        }
        
        return music.getMusicUrl();
    }

    @Override
    public int getTotalCount() {
        return musicMapper.getTotalCount();
    }

    @Override
    @Transactional
    public boolean addMusic(Music music) {
        music.setCreateTime(new Date());
        music.setStatus(1);
        return musicMapper.addMusic(music) > 0;
    }

    @Override
    @Transactional
    public boolean updateMusic(Music music) {
        music.setUpdateTime(new Date());
        return musicMapper.updateMusic(music) > 0;
    }

    @Override
    @Transactional
    public boolean deleteMusic(Long id) {
        return musicMapper.deleteMusic(id, new Date()) > 0;
    }
} 